#include "TrieTree.h"
int TrieTree_static::cnt = 1;
int TrieTree_static::pass[MAX] = { 0 };
int TrieTree_static::end[MAX] = { 0 };
int TrieTree_static::tree[MAX][26] = { 0 };

void TrieTree_static::insert(string word)
{
	int cur = 1;
	++pass[cur];
	for (int i = 0, path = 0; i < word.length(); ++i) {
		path = word.at(i) - 'a';
		if (tree[cur][path] == 0) {
			tree[cur][path] = ++cnt;
		}
		cur = tree[cur][path];
		pass[cur]++;
	}
	end[cur]++;
}

void TrieTree_static::biuld()
{
	TrieTree_static::cnt = 1;
}

int TrieTree_static::count(string word)
{
	int cur = 1;
	for (int i = 0, path = 0; i < word.length(); ++i) {
		path = word.at(i) - 'a';
		if (tree[cur][path] == 0) {
			return 0;
		}
		cur = tree[cur][path];
	}
	return end[cur];
}

bool TrieTree_static::deleteAll(string s)
{
	int cnt = TrieTree_static::count(s);
	if (cnt == 0) {
		return false;
	}
	int cur = 1;
	pass[cur] -= cnt;
	for (int i = 0, path; i < s.length(); ++i) {
		path = s.at(i) - 'a';
		cur = tree[cur][path];
		pass[cur] -= cnt;
	}
	end[cur] -= cnt;
	return true;
}

bool TrieTree_static::deleteStr(string s, int count)
{
	int cnt = TrieTree_static::count(s);
	if (cnt == 0) {
		return false;
	}
	int cur = 1;
	cnt = cnt < count ? cnt: count;
	pass[cur] -= cnt;
	for (int i=0,path;i<s.length();++i) {
		path = s.at(i) - 'a';
		cur = tree[cur][path];
		pass[cur] -= cnt;
	}
	end[cur] -= cnt;
	return true;
}

int TrieTree_static::prefixes(string s)
{
	int cur = 1;
	for (int i = 0, path; i < s.length(); ++i) {
		path = s.at(i) - 'a';
		if (tree[cur][path] == 0) {
			return 0;
		}
		cur = tree[cur][path];
	}
	return pass[cur];
}
